package com.heimali.happyreader.db.dao;

import java.util.List;

import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.heimali.happyreader.db.DBHelper;
import com.heimali.happyreader.utils.ArrayUtils;
import com.heimali.happyreader.utils.SystemUtils;

public abstract class BaseDao {
	private static final String TAG = "ListDao";
	protected static final int IN_MAX_COUNT = 30;
	
	protected String tableName;
	protected String getTable() {
		return tableName;
	} 
	
	public int delete(Object[] articleIDs) {
		int count = 0;
		String strIDs = "";
		synchronized (DBHelper.writeLock) {
			SQLiteDatabase db = DBHelper.getDatabase();
			try {
				while (articleIDs.length > 0) {
					List<Object[]> res = ArrayUtils.splice(articleIDs, 0, IN_MAX_COUNT);
					articleIDs = (Object[]) res.get(0);
					strIDs = TextUtils.join(",", (Object[]) res.get(1));
					String sql = "delete from " + getTable() + " where articleID in (" + strIDs + ")";
					// SystemUtils.Log(sql);
					db.execSQL(sql);
					count++;
				}
			} catch (SQLException e) {
				e.printStackTrace();
				SystemUtils.Log(TAG, e.getMessage());
			}
		}
		return count;
	}

	public int delete(String articleID) {
		int count = 0;
		synchronized (DBHelper.writeLock) {
			SQLiteDatabase db = DBHelper.getDatabase();
			try {
				count = db.delete(getTable(), "articleID=?", new String[] { articleID });
			} catch (SQLException e) {
				e.printStackTrace();
				SystemUtils.Log(TAG, e.getMessage());
			}
		}
		return count;
	}
}
